package com.com.cgq.data.exchenge;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.cgq.business.R;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by cgq on 2015/11/8.
 */
public class imageLoader {
    private ImageView mimageView;
    private String murl;
    private ListView mlistView;
    private Set<NewsAsyncTack> mtask;

    private LruCache<String,Bitmap> lruCache;
    public imageLoader(ListView listView){
        mlistView=listView;
        mtask=new HashSet<NewsAsyncTack>();
        int maxMemory=(int) Runtime.getRuntime().maxMemory();
        int cachSize=maxMemory/4;
        lruCache=new LruCache<String, Bitmap>(cachSize){
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }

    public void addBitmapToCache(String url,Bitmap bitmap){
        if (getBitmapfromCache(url)==null) {
            lruCache.put(url, bitmap);
        }
    }
    public Bitmap getBitmapfromCache(String url){
        return lruCache.get(url);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mimageView.getTag().equals(murl)) {
                mimageView.setImageBitmap((Bitmap)msg.obj);
            }
        }
    };

    public void showimageThread(ImageView imageView,final String url){
        mimageView=imageView;
        murl=url;
        new Thread(){
            public void run() {
                super.run();
                Bitmap bitmap=getBitmapFromUrl(url);
                Message message=Message.obtain();
                message.obj=bitmap;
                handler.sendMessage(message);
            }
        }.start();
    }

    public Bitmap getBitmapFromUrl(String urlString){
        Bitmap bitmap;
        InputStream inputStream = null;
        try {
            URL url=new URL(urlString);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            inputStream=new BufferedInputStream(connection.getInputStream());
            bitmap= BitmapFactory.decodeStream(inputStream);
            connection.disconnect();
            return bitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    public void showImageByAsyncTask(ImageView imageView,String url){

        Bitmap bitmap=getBitmapfromCache(url);

        if (bitmap==null) {
//			new NewsAsyncTack(url).execute(url);
            imageView.setImageResource(R.mipmap.icon);
        }else {
            imageView.setImageBitmap(bitmap);
        }
    }

    public void cancelAllTasks(){
        if (mtask!=null) {
            for (NewsAsyncTack task : mtask) {
                task.cancel(false);
            }
        }
    }

    public void loadImages(int start ,int end){
        for (int i = start; i < end; i++) {
            String url=ListDataAdapter.URLS[i];

            Bitmap bitmap=getBitmapfromCache(url);

            if (bitmap==null) {
                NewsAsyncTack task=new NewsAsyncTack(url);
                task.execute(url);
                mtask.add(task);
//				new NewsAsyncTack(imageView, url).execute(url);
            }else {
//				imageView.setImageBitmap(bitmap);
                ImageView imageView=(ImageView) mlistView.findViewWithTag(url);
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    private class NewsAsyncTack extends AsyncTask<String, Void, Bitmap> {

        //		private ImageView mimageView;
        private String murl;
        public NewsAsyncTack(String url){
//			mimageView=imageView;
            murl=url;
        }
        protected Bitmap doInBackground(String... arg0) {

            String url=arg0[0];

            Bitmap bitmap=getBitmapFromUrl( url);
            if (bitmap!=null) {

                addBitmapToCache(url, bitmap);
            }
            return bitmap;
        }

        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
//			if (mimageView.getTag().equals(murl)) {
//				mimageView.setImageBitmap(bitmap);
//			}
//			mimageView.setImageBitmap(bitmap);
            ImageView imageView=(ImageView) mlistView.findViewWithTag(murl);
            if (imageView!=null && bitmap!=null) {
                imageView.setImageBitmap(bitmap);
            }
            mtask.remove(this);
        }
    }
}
